package com.qianfeng.security.handlers;

import com.qianfeng.cache.RoleCache;
import com.qianfeng.pojo.BaseUser;
import com.qianfeng.pojo.SysMenu;
import com.qianfeng.pojo.SysRole;
import com.qianfeng.service.RoleService;
import com.qianfeng.utils.LoginUsersUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;

/*
*@Description:
*@author:刘哥
*@Date:86180 2022/9/16 14:23
*/
//SimpleUrlAuthenticationSuccessHandler 认证成功后的处理
@Component
public class MySuccessHandler extends SimpleUrlAuthenticationSuccessHandler {
    private RoleService roleService;

    private RoleCache roleCache;
    @Autowired
    public void setRoleService(RoleService roleService) {
        this.roleService = roleService;
    }
    @Autowired
    public void setRoleCache(RoleCache roleCache) {
        this.roleCache = roleCache;
    }

    /**
     * 授权
     * @param request
     * @param response
     * @param authentication
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
//        获取所有角色的权限
//        获取当前登录的角色
        BaseUser baseUser = (BaseUser) authentication.getPrincipal();
        Long userId = baseUser.getUserId();
//        获取当前用户的角色
        List<SysRole> roleList=roleService.findRolesByUserId(userId);
//        根据角色id查询权限数据、
        roleList = roleList.stream().map(role -> roleCache.get(role.getRoleId())).collect(Collectors.toList());
//        这个是我们自己使用,和security没有关系
        baseUser.setRoleList(roleList);
//        告诉security当前用户的权限
        List<SimpleGrantedAuthority> authorities = roleList.stream().flatMap(role -> role.getMenuList().stream()).map(SysMenu::getPerms).filter(s -> StringUtils.hasText(s)).map(SimpleGrantedAuthority::new).collect(Collectors.toList());
//        生成用户的权限数据并返回给用户
        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(baseUser, baseUser.getPassword(), authorities);
        SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);

        super.onAuthenticationSuccess(request, response, authentication);
    }
}
